<template>
  <div id="login">
    <ValidateForm @form-submit="handleFormSubmit">
      <ValidateInput :rules="emailRules" v-model="emailVal" placeholder="请输入邮箱地址">
        <label class="label pb-10">邮箱地址：</label>
      </ValidateInput>
      <ValidateInput :rules="passwordRules" v-model="passwordVal" type="password" placeholder="请输入密码">
        <label class="label pb-10">密 码：</label>
      </ValidateInput>
      <template #submit="">
        <button class="btn btn-danger">登 录</button>
      </template>
    </ValidateForm>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
import ValidateInput, { ruleProps } from '@/components/Form/ValidateInput.vue';
import ValidateForm from '@/components/Form/ValidateForm.vue';
import createMessage from '@/components/createMessage';
const emailReg = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;

export default defineComponent({
  name: 'login',
  components: { ValidateInput, ValidateForm },
  setup() {
    const emailRef = reactive({
      val: '',
      error: false,
      message: ''
    });
    const emailVal = ref('liudehua@123.com');
    const passwordVal = ref('');
    const rangeLength = [6, 18];
    const emailRules: ruleProps = [
      {
        type: 'required',
        message: '电子邮箱地址不能为空'
      },
      {
        type: 'email',
        message: '请输入正确格式的邮箱',
        validate: (val: string): boolean => {
          return emailReg.test(val);
        }
      },
      {
        type: 'range',
        message: `请输入${rangeLength[0]} - ${rangeLength[1]}长度的值`,
        validate: (val: string): boolean => {
          return val.length >= rangeLength[0] && val.length <= rangeLength[1];
        }
      }
    ];
    const passwordRules: ruleProps = [
      {
        type: 'required',
        message: '密码不能为空'
      },
      {
        type: 'range',
        message: `请输入${rangeLength[0]} - ${rangeLength[1]}长度的值`,
        validate: (val: string): boolean => {
          return val.length >= rangeLength[0] && val.length <= rangeLength[1];
        }
      }
    ];

    const validateEmail = () => {
      if (emailRef.val.trim() === '') {
        emailRef.error = true;
        emailRef.message = '值不能为空！';
      } else if (!emailReg.test(emailRef.val.trim())) {
        emailRef.error = true;
        emailRef.message = '不符合邮箱格式';
      } else {
        emailRef.error = false;
        emailRef.message = '';
      }
    };
    const route = useRoute();
    const router = useRouter();
    const store = useStore();
    const handleFormSubmit = (val: boolean) => {
      console.log('handleFormSubmit', val);
      // login success
      if (val) {
        // store.commit('login');
        /* 测试数据，viking@qq.com viking */
        /* 测试数据，111@test.com 111111 */
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        };
        // store.dispatch('login', payload).then(res => {
        //   console.log(res, 'token');
        //   router.push({ name: 'home' });
        // });
        store
          .dispatch('loginAndFetchCurrentUser', payload)
          .then(() => {
            createMessage('登录成功，跳转首页', 'success');
            setTimeout(() => {
              router.push('/');
            }, 200);
          })
          .catch(err => {
            console.log(err.response?.data?.error);
          });
      }
    };
    return { route, emailRef, validateEmail, emailRules, emailVal, passwordRules, passwordVal, handleFormSubmit };
  }
});
</script>

<style></style>
